// socket功能
/**
 * STOMP整个通讯流程：

 1、首先客户端与服务器建立 HTTP 握手连接，连接点 EndPoint 通过 WebSocketMessageBroker 设置。（这是下面操作的前提）
 2、客户端通过 subscribe 向服务器订阅消息主题（”/topic”或者“/all”），topic在本demo中是聊天室（单聊+多聊）的订阅主题，all是群发的订阅主题
 3、客户端可通过 stompClient.send 向服务器发送消息，消息通过路径 /app/chat或者/appAll达到服务端，服务端将其转发到对应的Controller（根据Controller配置的 @MessageMapping(“/chat")或者@MessageMapping(“/chaAll") 信息）
 4、服务器一旦有消息发出，将被推送到订阅了相关主题的客户端（Controller中的@SendTo(“/topic”）或者Controller中的@SendTo(“/all”)表示将方法中 return 的信息推送到 /topic 主题）。还有一种方法就是利用 messagingTemplate 发送到指定目标 （messagingTemplate.convertAndSend(destination, response);
 */
import SockJS from "sockjs-client";
import Stomp from "stompjs";
import store from "./store";
import {getToken, getUser} from "@/utils/auth";
import {Message, Notification} from "element-ui";
import state from "@/store/state";

let sockJS = null
let stompClient = null
let username = null
let userId = null
let userProfile = null

export function socketConnect(event) {
    // 连接socketjs的endpoint
    sockJS = new SockJS('http://localhost:8650/ws/chatroom');

    // 获取STOMP子协议的客户端对象
    stompClient = Stomp.over(sockJS);

    let header = {
        'Authorization': getToken(),
        'username': JSON.parse(getUser()).username
    }

    stompClient.connect(header, onConnected, onError)

    // 关闭控制台打印
    stompClient.debug = null

    username = JSON.parse(getUser()).username;
    userId = JSON.parse(getUser()).userId
    userProfile = JSON.parse(getUser()).userProfile

}

// 向服务器发起websocket连接
function onConnected() {
    console.log('连接成功')

    stompClient.subscribe('/user/topic/touser',responseCallback, onFailed);

    stompClient.subscribe('/topic/chatroom', onMessageReceived);

    stompClient.subscribe('/chatroom/sendtotest', onMessageReceived);

    stompClient.subscribe('/chatroom/sendMessageTest', onMessageReceived);

    stompClient.subscribe('/chatroom/sendMsgGroup', onMessageReceived);

    //接收频率
    stompClient.heartbeat.incoming = 0
    //发送频率
    stompClient.heartbeat.outgoing = 0

    // stompClient.send('/chatroom/addUser', {},
    //     JSON.stringify({
    //         fromId: userId,
    //         fromName: username,
    //         from_profile: userProfile,
    //         toId: '-1',
    //         toName: 'all',
    //         messageTypeId: '1',
    //         createTime: new Date()
    //     })
    // );
    Message({
        message: '欢迎来到LucienIM',
        type: 'success',
        duration: 2 * 1000
    })
    state.socketStatus = true
}
function onFailed(frame) {
    console.log("Failed: " + frame);
}

function responseCallback(frame) {
    console.log("得到的消息 msg=>" + frame.body);
    console.log(frame)
    //接收到服务器推送消息，向服务器定义的接收消息routekey路由rk_recivemsg发送确认消息
}
/**
 * 用户之间发送消息
 * @param content 消息内容
 * @param params
 *  {
 *      friend_id: '',      好友ID
        friendName: '',     好友昵称
 *  }
 */
export function sendMessage(content, params) {
    console.log('发送消息', stompClient)
    if (content && stompClient) {
        var chatMessage = {
            fromId: userId,
            fromName: username,
            fromProfile: userProfile,
            toId: params.friend_id,
            toName: params.friendName,
            messageTypeId: '2',
            content: content,
            createTime: new Date()
        };
        stompClient.send("/chatroom/sendMessageTest", {}, JSON.stringify(chatMessage));
    }
    return chatMessage;
}

/**
 * 发送群聊信息
 */
export function sendGroupMsg(params) {
    console.log('发送群聊信息')
    if (stompClient) {
        var groupMsg = {
            groupId: params.groupId,
            userId: params.userId,
            username: params.username,
            userProfile: params.userProfile,
            content: params.content,
            messageTypeId: params.messageTypeId,
            createTime: new Date(),
        };
        stompClient.send("/chatroom/sendMsgGroup", {}, JSON.stringify(groupMsg));
    }
}

// 消息回调
function onMessageReceived(payload) {
    console.log(payload)
    // var message = JSON.parse(payload.body);
    // console.log('消息回调',message)
    // if(message.messageTypeId === 1) {
    //     console.log(message.fromName + ' 上线~!');
    // } else if (message.messageTypeId === 3) {
    //     console.log(message.fromName + ' 离线了!');
    // } else {
    //     console.log('websocket接受消息')
    // }
}

// 连接错误
function onError(error) {
    Notification.error({
        title: 'websocket错误',
        message: '正在重连...'
    })
    socketConnect()
    console.log(error)
}

export function disConnect() {
    stompClient.disconnect()
}
